package com.ruoyi.web.controller.business;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.ApiLoginUser;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@Api("广告管理系统类API接口")
@RestController
@RequestMapping("/api")
public class ApiLoginController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private AuthenticationManager authenticationManager;

    final static Pattern partern = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");

    /**
     * 验证输入的邮箱格式是否符合
     * @param email
     * @return 是否合法
     */
    public static boolean emailFormat(String email){
        boolean isMatch = partern.matcher(email).matches();
        return isMatch;
    }


    /**
     * app登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("app登录")
    @PostMapping("/loginApp")
    public AjaxResult loginApp(@RequestBody LoginBody loginBody) {

        // 用户验证
        Authentication authentication = null;

        if (StringUtils.isEmpty(loginBody.getUsername()) || StringUtils.isEmpty(loginBody.getPassword()))
        {
            return AjaxResult.error("用户名或密码为空！");
        }

        if (!loginBody.getUsername().equals("admin") && emailFormat(loginBody.getUsername()))
        {
            return AjaxResult.error("邮箱格式不正确！");
        }

        if (null == userService.selectUserByUserName(loginBody.getUsername()))
        {
            return AjaxResult.error("用户不存在！");
        }

        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            return AjaxResult.error("密码错误！");
        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginApi(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, "Bearer "+token);
        return ajax;
    }

    /**
     * app注册
     *
     * @param loginBody 注册信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("app注册")
    @PostMapping("/registerApp")
    public AjaxResult registerApp(@RequestBody LoginBody loginBody) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(loginBody.getUsername());
        if (!userService.checkUserNameUnique(sysUser)) {
            return error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        sysUser.setUserName(loginBody.getUsername());
        sysUser.setNickName(loginBody.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(loginBody.getPassword()));
        userService.insertUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 后台注册
     *
     * @param loginBody 注册信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("后台注册")
    @PostMapping("/registerBackground")
    public AjaxResult registerBackground(@RequestBody LoginBody loginBody) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(loginBody.getUsername());
        if (!userService.checkUserNameUnique(sysUser)) {
            return error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        sysUser.setUserName(loginBody.getUsername());
        sysUser.setNickName(loginBody.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(loginBody.getPassword()));
        userService.insertUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 获取验证码
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("获取验证码")
    @GetMapping("/verificationCode/{username}")
    public AjaxResult login(@PathVariable String username) {
        System.out.println(username);
        return AjaxResult.success();
    }

    /**
     * 邮箱验证
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("邮箱验证")
    @PostMapping("/forgotEmail")
    public AjaxResult forgotEmail(@RequestBody LoginBody loginBody) {
        if (null != loginBody.getCode() && "000000".equals(loginBody.getCode())) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("验证码错误！");
        }
    }

    /**
     * 找回密码 - 设置新的账户密码
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("找回密码 - 设置新的账号密码")
    @PostMapping("/changePassword")
    public AjaxResult changePassword(@RequestBody ApiLoginUser apiLoginUser) {
        if(!apiLoginUser.getPassword().equals(apiLoginUser.getPasswordVerify())){
            return AjaxResult.error("两次输入密码不一致");
        }
        if (userService.resetUserPwd(apiLoginUser.getUsername(), SecurityUtils.encryptPassword(apiLoginUser.getPassword())) > 0) {
            return success();
        }
        return AjaxResult.success();
    }


}
